package com.idcheck.rechcustoms;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

//import aar.test.tessocr.baseApplication.BaseApplication;
import utils.OtherUtil;
import utils.PrefUtils;

public class AdminForInternalLoginActivity extends AppCompatActivity {

    private EditText companyMobile;
    private EditText password;
    private String strPassword="";

    private int adminId = 0;
    private String adminTel = "";
    private int companySeqId = 0;



    private CountDownTimer mTimer=null; //UI计时
    private volatile long resetTimeStamp = 0;
    private volatile long brightTimeStamp = 0;
    private volatile long mCountSetting = 0;
    private volatile long countTimeStamp = 0;

    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;


    private boolean mVisible;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_for_internal_login);
        companyMobile = findViewById(R.id.savePhone);
        password = findViewById(R.id.password_inner);
        mVisible = true;
        if(getSupportActionBar()!=null){

            getSupportActionBar().hide();

        }
        hideBottomUIMenu();

        initTimer();

        findViewById(R.id.saveback1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();
            }
        });


        findViewById(R.id.saveback2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();
            }
        });
        findViewById(R.id.saveback1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();
            }
        });

        findViewById(R.id.confirm2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phnumber=companyMobile.getText().toString();

                String pass=password.getText().toString();

                if(TextUtils.isEmpty(phnumber)){

                    Toast.makeText(AdminForInternalLoginActivity.this,"电话号码不能为空",Toast.LENGTH_LONG).show();

                    return ;
                }

                if(11!=phnumber.length()){

                    Toast.makeText(AdminForInternalLoginActivity.this,"无效的电话号码",Toast.LENGTH_LONG).show();

                    return ;
                }


                if(TextUtils.isEmpty(pass)){
                    Toast.makeText(AdminForInternalLoginActivity.this,"密码不能为空",Toast.LENGTH_LONG).show();

                    return ;

                }

                resetTimeStamp = System.currentTimeMillis();

                resetTimeStamp = System.currentTimeMillis();
                new FetchSaveAuthTask(phnumber, pass).execute();
                password.setText("");
                //findViewById(R.id.confirm1).setEnabled(false);
            }
        });
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //eventbus
        initView();
    }

    private void initView(){

        this.resetTimeStamp = 0;
        this.brightTimeStamp = 0;
        this.mCountSetting = 0;
        this.countTimeStamp = 0;

        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }

    private void resetViewMessage(){
        Message message = new Message();
        message.what=1200;
        EventBus.getDefault().post(message);
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }
    private void delayedHide(int delayMillis) {
    }
    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay

    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mVisible = true;


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unInitTimer();
    }
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (9999999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!AdminForInternalLoginActivity.this.isFinishing()) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 \n HH:mm:ss");// HH:mm:ss
//获取当前时间
                        Date date = new Date(System.currentTimeMillis());
                        TextView datetext = (TextView)findViewById(R.id.textDate);
                        datetext.setText(simpleDateFormat.format(date));
                        TextView weektext = (TextView)findViewById(R.id.textWeek);
                        weektext.setText(getWeek());
                        if(resetTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - resetTimeStamp;
                            if(timeOut > 180000){
                                resetView();
                            }
                        }


                        if(countTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - countTimeStamp;
                            if(timeOut > 3000){
                                mCountSetting = 0;
                                countTimeStamp = 0;
                            }
                        }

                        int hours = date.getHours();
                        int minutes = date.getMinutes();
                        int seconds = date.getSeconds();


                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public static String getWeek(){
        Calendar cal = Calendar.getInstance();
        int i = cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message) {
        switch (message.what) {
            case 1600:
                EventMessageForSaveAuth(message.obj);
                break;

            case 1200:
                restartApplication();
                break;
            default:
                EventMessageForError(message.what);
                break;

        }
    }
    private void resetView(){
        finish();
    }
    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    private void EventMessageForSaveOpen(Object obj){
        try{

            findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }else{
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.error);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("请检查网络");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }
    }
    private void EventMessageForSaveAuth(Object obj){
        try{


            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                PrefUtils.setString(this, "adminid", result.getJSONObject("data").getString("id"));
                PrefUtils.setString(this, "cabinetid", result.getJSONObject("data").getString("cabinetId"));
                PrefUtils.setString(this, "phone", result.getJSONObject("data").getString("username"));

                //PrefUtils.setString(this, "phone", result.getJSONObject("data").getString("cabinetid"));
                startActivity(new Intent(AdminForInternalLoginActivity.this, ChioceCabActivity.class));
//                companyMobile = findViewById(R.id.savePhone);
//                password.setText("");
//                findViewById(R.id.step11).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                findViewById(R.id.step12).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
//
//                int count = result.getJSONObject("data").getInt("count");
//                if(count != 0){
//                    TextView saveresult = findViewById(R.id.saveresult);
//                    String text = "有"+String.valueOf(count)+"空位";
//                    saveresult.setText(text);
//                    saveresult.setTextColor(Color.BLACK);
//                    findViewById(R.id.savesubmit).setEnabled(true);
//                    findViewById(R.id.ordersubmit).setEnabled(true);
//                }else{
//                    TextView saveresult = findViewById(R.id.saveresult);
//                    String text = "暂无空位";
//                    saveresult.setText(text);
//                    saveresult.setTextColor(Color.RED);
//                    findViewById(R.id.savesubmit).setEnabled(false);
//                    findViewById(R.id.ordersubmit).setEnabled(false);
//                }
                resetTimeStamp = System.currentTimeMillis();
            }else{
                findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.warning);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            resetView();
        }
    }
    private void EventMessageForError(int what){
        switch(what){
            case 1101:
                Toast.makeText(AdminForInternalLoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                break;
            case 1301:
//                if(OtherUtil.isKeyboardActive(getWindow())){
//                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
//                }
                resetView();
                break;
            case 1401:
                if(OtherUtil.isKeyboardActive(getWindow())){
                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
                }
                resetView();
                break;
            case 1501:
                Toast.makeText(AdminForInternalLoginActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;
            case 1701:
                Toast.makeText(AdminForInternalLoginActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;

        }
    }
}